import { defineComponent, reactive, ref,watch,onMounted} from "vue";
import styles from "./insure.module.scss";
import useSms from "@/hooks/useSms";
import NeedLogin from "@/components/NeedLogin/NeedLogin";
import { $orderSingleCreate,$commonCategory ,$orderSingleRecordScreen} from "@/apis/api";
import validateInstance from "@/libs/validate/validate";
import { Toast } from "@nutui/nutui";
import { useStore as useScreenRecordingStore } from '@/store/screenRecording';
import InsureConfirm from "./components/InsureConfirm/InsureConfirm";
import { record } from 'rrweb';
import to from "await-to-js";
import usePay from "@/hooks/usePay";
export default defineComponent({
  setup() {
    const pay = usePay();
    const screenRecordingStore = useScreenRecordingStore();
    const InsureConfirmRef = ref(null as any);
    const sms = useSms();
    const navs = reactive({
      list: ['填写信息', '产品特色', '理赔服务', '关于我们'],
      actived: 0,
    })
    const state = reactive({
      columns:[],
      show:false,
      identityName:'',
    } as any)
    const form = ref({
      number:"female_8505670151",
      operate_time:"2023-12-11",
      app_type:"wechat",
      app_type_name:"微信公众号",
      start_hour:"",
      end_hour:"",
      applicant_sex:"2",
        applicant_name: '郑',
        applicant_id_type: '111',
        applicant_id_no: '330327199204200017',
        applicant_mobile: '13739277173',
        applicant_email:'z1339861663@163.com',
        applicant_birthday:"2002-4-12",
        province_id:"1",
        city_id:"2",
        area_id:"3",
        address:'sadfasdasdfdsa',
        product_id:"42",
        code:"",
        key:"",
      insured:[
        {
          identity: '17',
          name: '郑',
          id_type: '111',
          id_no: '330327199204200017',
          mobile: '18860054213',
          province_id: '1',
          city_id: '2',
          area_id:'3',
          address: 'adsfaf',
        }
      ]
    } as any)
    const getBirthday = (idCard:any)=>{
     // 提取出生年月日的部分
     let birthday = idCard.substring(6, 14);
        
     // 将八位数字转换为年月日格式
     let year = birthday.substring(0, 4);
     let month = birthday.substring(4, 6);
     let day = birthday.substring(6);
     
     // 返回出生日期
     return year + '-' + month + '-' + day;
    }
    const jumpScroll = (e:any) =>{
        let targetBox = document.getElementById(e);
        let top:any = targetBox?.offsetTop;
        document.documentElement.scrollTop =top;
    }
    const getStartDate = () => {
      let year = "";
      let month = "";
      let date = "";
      let start_date = new Date();
      start_date.setDate(start_date.getDate() + 1);
      year = String(start_date.getFullYear());
      month = String(start_date.getMonth() + 1).padStart(2, "0");
      date = String(start_date.getDate()).padStart(2, "0");
      return `${year}-${month}-${date}`;
    }
        //下单
        const submit = () => {
          try {
            if (!form.applicant_name) {
              throw "请填写投保人姓名!";
            }
            // if (!validateInstance.test(insureStore.params.applicant.id_no, 'idcard')) {
            //   throw "请填写正确的投保人身份证号!";
            // }
            if (!form.address) {
              throw "请选择投保人户口所在地!";
            }
            if (!form.applicant_mobile) {
              throw "请填写投保人手机号!";
            }
            if (form.applicant_mobile?.length !== 11) {
              throw "投保人手机号格式不正确!";
            }
            if (!form.code) {
              throw "请填写投保人手机验证码!";
            }
            form.insured.forEach((item: any, index: number) => {
              if (!item.identity) {
                throw `请选择被保人与缴费人关系!`;
              }
              if (!item.name) {
                throw `请输入被保人姓名!`;
              }
              if (!validateInstance.test(item.id_no, 'idcard')) {
                throw `请填写正确的被保人身份证号!`;
              }
              if (!item.address) {
                throw `请选择被保人户口所在地!`;
              }
              if (!item.mobile) {
                throw `请填写被保人手机号!`;
              }
              if (item?.mobile.length !== 11) {
                throw `被保人手机号格式不正确!`;
              }
            })
          } catch (err: any) {
            Toast.fail(err);
            return;
          }
          InsureConfirmRef.value.open();
        }
    const getEndDate = () => {
      let year = "";
      let month = "";
      let date = "";
      let end_date = new Date();
      end_date.setFullYear(end_date.getFullYear() + 1);
      year = String(end_date.getFullYear());
      month = String(end_date.getMonth() + 1).padStart(2, "0");
      date = String(end_date.getDate()).padStart(2, "0");
      return `${year}-${month}-${date}`;
    }
    const saveScreenRecord = async (order_no: string) => {
      let params: any = {};
      const event = encodeURIComponent(JSON.stringify(screenRecordingStore.events.order));
      params.order_no = order_no;
      params.screen_record = event;
      params.scene = 'order';
      Toast.loading('记录提交中...', {
        id: 'screenSave',
        duration: 0,
      })
      const [err, res]: any = await to($orderSingleRecordScreen(params));
      if (!err) {
        screenRecordingStore.initEvents('order');
      }
      Toast.hide('screenSave');
    }
        //监听生日
        watch(() => form.value.applicant_id_no, (nv) => {
          if(nv.length > 17)
          {
            if (!validateInstance.test(nv, 'idcard')) {
              throw "请填写正确的投保人身份证号!";
            }
            else
            {
               form.value.applicant_birthday = getBirthday(nv);
            }
          }
      })
      const crateWeb = () => {
        let events: any[] = [];
        record({
          emit(event) {
            // 用任意方式存储 event
            events.push(event);
            screenRecordingStore.addEvents(events, 'order');
          }
        })
      }
      onMounted(async () => {
        const [err, res]: any = await to($commonCategory({
          type: 'sys_family_relation'
        }))
        if (!err) {
          console.log("res",res);
           res.data.forEach((item:any)=>{
              if(item.dict_label == "本人" || item.dict_label == "母亲" || item.dict_label == "夫妻" || item.dict_label == "女儿")
              {
                 state.columns.push({
                    text:item.dict_label,
                    value:item.dict_code,
                 })
              }
           })
        }
        screenRecordingStore.initEvents('order');
        crateWeb();
      })
    // 填写信息
    const SignForm = () => (
      <div class={styles['sign-form']}>
        <div class={styles['sign-form-header']}>
          <div class={styles['header-item']}>
            <span class={styles['item-label']}>生效方式</span>
            <span class={[styles['item-value'], styles.thiner]}>承保次日零时生效</span>
          </div>
          <div class={styles['header-item']}>
            <span class={styles['item-label']}>生效时间</span>
            <span class={styles['item-value']}>{getStartDate()} 00:00:00</span>
          </div>
          <div class={styles['header-item']}>
            <span class={styles['item-label']}>终止时间</span>
            <span class={styles['item-value']}>{getEndDate()} 23:59:59</span>
          </div>
        </div>
        <div class={styles['sign-form']}>
          <div class={styles['sign-form-title']}>
            <div class={styles['header-index']}>1</div>
            <span>投保人信息</span>
          </div>
          <div class={styles['sign-form-rows']}>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>投保人姓名</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.applicant_name}
                  placeholder="请输入投保人姓名"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>证件类型</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.applicant_id_type}
                  placeholder="请选择证件类型"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>证件号</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.applicant_id_no}
                  placeholder="请输入证件号"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>手机号</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.applicant_mobile}
                  placeholder="用于获取承保信息"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>验证码</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.code}
                  placeholder="请输入验证码"
                />
              </div>
              <div class={styles['dynacode-btn']} onClick={() => sms.sendSms(form.value.applicant_mobile)}>{sms.state.countdown > 0 ? sms.state.countdown  + 's' : '发送动态码'}</div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>邮箱</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.applicant_email}
                  placeholder="用于获取电子保单"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>出生日期</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.applicant_birthday}
                  placeholder="默认填写出生日期"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>联系地址</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.address}
                  placeholder="请选择联系地址"
                  readonly
                />
              </div>
            </div>
          </div>
        </div>
        <div class={styles['sign-form']}>
          <div class={styles['sign-form-title']}>
            <div class={styles['header-index']}>2</div>
            <span>被投保人信息</span>
          </div>
          <div class={styles['sign-form-rows']}>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>与被保人关系</span>
              <div class={styles['row-value']}  onClick={() => { 
                 state.show = true;
               }}>
                <input
                  v-model={state.identityName}
                  placeholder="请选择"
                  readonly
                />
              </div>
            </div>
          </div>
          <div class={styles['sign-form-rows']}>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>被投保人姓名</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.insured[0].name}
                  placeholder="请输入投保人姓名"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>证件类型</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.insured[0].id_type}
                  placeholder="请选择证件类型"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>证件号</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.insured[0].id_no}
                  placeholder="请输入证件号"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>手机号</span>
              <div class={styles['row-value']}>
                <input
                  v-model={form.value.insured[0].mobile}
                  placeholder="用于获取承保信息"
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>联系地址</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.insured[0].id_type}
                  placeholder="请选择联系地址"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>街道/乡/镇</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.insured.id_type}
                  placeholder="请选择"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>社区/村</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.insured.id_type}
                  placeholder="请选择"
                  readonly
                />
              </div>
            </div>
            <div class={styles['sign-form-row']}>
              <span class={styles['row-label']}>客户声明</span>
              <div class={styles['row-value']}>
                <input
                  value={form.value.insured[0].id_type}
                  placeholder="请选择"
                  readonly
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    )
    return () => (
      <div class={styles.insure}>
        <div class={styles.body_box}>
        <div class={styles['insure-head']}>
          <img class={styles['insure-head-image']} src={require("@/assets/images/insure-head-image.png")} />
          <div class={styles['insure-background']}></div>
          <div class={styles.ads}>
            <span class={styles.ad1}>康乃馨女性健康公益保险</span>
            <span class={styles.ad2}>关爱·女性健康</span>
            <span class={styles.ad3}>由浙江省妇女联合会指导</span>
            <span class={styles.ad4}>浙江省妇女儿童基金会发起执行的公益项目</span>
          </div>
          <div class={styles.card}>
            <div class={styles['card-header']}>
              <span class={styles['card-title']}>保障详情</span>
              <div class={styles['card-moredetail']}>
                <span>更多详情</span>
                <img class={styles['arrow-right']} src={require("@/assets/images/arrow-right.png")} />
              </div>
            </div>
            <div class={styles['card-rows1']}>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>女性特定疾病保险金</span>
                <span class={styles['card-row-value']}>6万元</span>
              </div>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>女性乳腺癌保险金</span>
                <span class={styles['card-row-value']}>5万元</span>
              </div>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>女性原位癌保险金</span>
                <span class={styles['card-row-value']}>2万元</span>
              </div>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>意外身故或残疾保险金</span>
                <span class={styles['card-row-value']}>2万元</span>
              </div>
            </div>
            <div class={styles['card-rows2']}>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>保障对象:</span>
                <span class={styles['card-row-value']}>16-60周岁女性</span>
                {/* 凡16-60周岁、身体健康、能正常工作或生活的女性（化工行业，长期接触电磁辐射、化学制剂等工种除外）职业类别1-3类的，可作为被保险人购买本保险。 */}
              </div>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>保险期限:</span>
                <span class={styles['card-row-value']}>一年</span>
                {/* 一年，具体生效日以保单载明为准。本公司对合同应负的保险责任自保单生效日零时起至期满日二十四时止。 */}
              </div>
              <div class={styles['card-row']}>
                <span class={styles['card-row-label']}>份数限制:</span>
                <span class={styles['card-row-value']}>每保险年度每一被保险人最高限投保1份</span>
              </div>
            </div>
          </div>
        </div>
        <div class={styles['navs']}>
          {
            navs.list.map((item: any, index: number) => (
              <div class={[styles['navs-item'], navs.actived === index && styles.actived]} onClick={() => { 
                navs.actived = index 
                }}>
                <span>{item}</span>
              </div>
            ))
          }
        </div>
        {
           navs.actived === 0 && <SignForm />
        }
        {
           navs.actived === 1 && ( <div style={{width:"100%"}}>
           <nut-image src={require("@/assets/images/productFeaturesImage.png")} width='100%' fit="cover"></nut-image>
        </div>)
        }
        {
          navs.actived === 2 && (
            <div style={{width:"100%"}}>
            <nut-image src={require("@/assets/images/claimsService.png")} width='100%' fit="cover"></nut-image>
         </div>
          )
        }
        {
           navs.actived === 3 && (
            <div style={{width:"100%"}}>
            <nut-image src={require("@/assets/images/about.png")} width='100%' fit="cover"></nut-image>
         </div>
           )
         }
        </div>
        <div class={styles.footer_box}>
             <div class={styles.order_box}>
               <span>我的订单</span>
             </div>
             <div class={styles.customerservice_box}>
             <span>客服</span>
             </div>
             <div class={styles.title_box}>
                <span class={styles.title_one}>¥</span>
                <span class={styles.money_box}>128.00</span>
                <span class={styles.title_two}>元/人/年</span>
             </div>
             <div class={styles.btn_box} onClick={()=>{

              InsureConfirmRef.value.open();
           
             }}>
                 <span>立即投保</span>
             </div>
        </div>
        <NeedLogin />
        <InsureConfirm ref={InsureConfirmRef} form={form.value} state={state} onConfirm={() => {
                     form.value.start_hour = new Date(getStartDate()).getTime();
                    form.value.end_hour = new Date(getEndDate()).getTime();
                   $orderSingleCreate({ ...form.value, key: sms.state.key }).then(async (res: any) => {
                      console.log("123",res);
                    InsureConfirmRef.value.close();
                    await saveScreenRecord(res?.data?.order_no);
                    pay.submit(res?.data?.out_trade_no, res?.data?.order_no);
                  }).finally(() => {
                    Toast.hide('insure');
                  })
        }} />
        <nut-picker   v-model:visible={state.show} columns={state.columns} title="请选择证件类型" onConfirm={(e:any)=>{
              state.identityName = e.selectedOptions[0].text;
              form.value.insured[0].identity = e.selectedValue[0];   
        }} onCancel={()=>{
               state.show = false;
         }}>
        </nut-picker>
          {/* <Popup ref={popupRef} content={{
             picker:()=>(
                  <Picker title="与投保人关系" columns={state.colums} onCancel={()=> popupRef.value.close()} onConfirm={(e:any)=>{
                      console.log("e",e);
                  }}></Picker>
              )
          }}>

          </Popup> */}
      </div>
    )
  }
})